package com.vpen.iot.controller;

import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.X509v3CertificateBuilder;
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
import org.bouncycastle.crypto.params.AsymmetricKeyParameter;
import org.bouncycastle.crypto.util.PrivateKeyFactory;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.jcajce.JcaPEMWriter;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;

import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.Security;
import java.security.cert.X509Certificate;
import java.util.Date;

public class GenerateCertificate8 {

    public static void main(String[] args) throws Exception {
        Security.addProvider(new BouncyCastleProvider());

        // 设置日期
        Date today = new Date();
        Date yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000L);
        Date tenYearsLater = new Date(today.getTime() + 3650L * 24 * 60 * 60 * 1000);

        // 生成 RSA 密钥对
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(4096);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        // 构建证书
        X500Name issuer = new X500Name("CN=JetProfile CA");
        X500Name subject = new X500Name("CN=MoYuno-from-2022-07-25");

        X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(
                issuer,
                BigInteger.valueOf(System.currentTimeMillis()),
                yesterday,
                tenYearsLater,
                subject,
                keyPair.getPublic()
        );

        ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSA").setProvider("BC").build(keyPair.getPrivate());
        X509CertificateHolder certHolder = certBuilder.build(contentSigner);

        X509Certificate certificate = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certHolder);

        // 将私钥转换为 PKCS#1 格式并写入文件
        try (JcaPEMWriter writer = new JcaPEMWriter(new OutputStreamWriter(new FileOutputStream("ca.key")))) {
            // 将私钥转换为 PKCS#1 格式
            PrivateKeyInfo privateKeyInfo = PrivateKeyInfo.getInstance(keyPair.getPrivate().getEncoded());

            AsymmetricKeyParameter parameter = PrivateKeyFactory.createKey(privateKeyInfo.getEncoded());

            writer.writeObject(parameter);
//            System.out.println();
        }

        // 将证书写入文件
        try (JcaPEMWriter writer = new JcaPEMWriter(new OutputStreamWriter(new FileOutputStream("ca.crt")))) {
            writer.writeObject(certificate);
        }
    }
}
